
import { vue, axios} from '@core';
import restPath from "@views/fabric/api/file";

import useCanvas from "@views/fabric/Canvas/useCanvas";
import { getImageDataURL, getImageText } from "@views/fabric/utils/image";
import useHandleTemplate from "@views/fabric/hooks/useHandleTemplate";
import useHandleCreate from "@views/fabric/hooks/useHandleCreate";
import useCanvasScale from "@views/fabric/hooks/useCanvasScale";
import { useTemplatesStore } from "@views/fabric/store";
import { loadSVGFromString } from '@views/fabric/extension/parser/loadSVGFromString'
// import axios from 'axios'; // 确保你已经安装并导入了axios



const applyStyle = (el, style) => {
  Object.entries(style).forEach(([property, value]) => {
    el.style[property] = value;
  });
};

const removeStyle = (el, style) => {
  Object.entries(style).forEach(async ([property, _]) => {
    el.style[property] = "";
  });
};

const defaultUpload = async (files, uploadUrl) => {
  const fileAccept = ".pdf,.psd,.cdr,.ai,.svg,.jpg,.jpeg,.png,.webp,.json";
  const { addTemplate } = useHandleTemplate();
  const { createImageElement } = useHandleCreate();
  const templatesStore = useTemplatesStore();
  const { setCanvasTransform } = useCanvasScale();
  Array.from(files).forEach(async (file) => {
    console.log("file", file);
    //   上传到服务端
    // const formData = new FormData();
    // formData.append('image', file);
    //   axios.post(uploadUrl, formData, {
    //     headers: {
    //       'Content-Type': 'multipart/form-data',
    //     },
    //   })
    //     .then((response) => {
    //       // 这里可以触发某个事件或者调用回调
    //       console.log('Image uploaded: ', response.data);
    //     })
    //     .catch((error) => {
    //       console.error('Upload error: ', error);
    //     });

    const [canvas] = useCanvas();
    const curFileSuffix = file.name.split(".").pop();
    if (!fileAccept.split(",").includes(`.${curFileSuffix}`)) return;
    if (curFileSuffix === "svg") {
      const dataText = await getImageText(file);
      const content = await loadSVGFromString(dataText);
      canvas.add(...content.objects);
      canvas.renderAll();
    }
    if (curFileSuffix === "json") {
      const dataText = await getImageText(file);
      const template = JSON.parse(dataText);
      addTemplate(template);
    }
    if (["jpg", "jpeg", "png", "webp"].includes(curFileSuffix)) {
      const dataURL = await getImageDataURL(file);
      createImageElement(dataURL);
    }

    let params = {
      file: file, 
      suffix: curFileSuffix
    };
    axios
        .post(restPath.file.uploadFile,params)
        .then((res1) => {
          if (res1 && res1.data.code === 200) {
            const template = res1.data.data;
            if (!template) return;
             templatesStore.addTemplate(template);
            setCanvasTransform();
          }
        })
        .catch((e) => {
          console.log("查询出错：" + e);
        });
  });
};

const dropImageDirective = {
  mounted(el, binding) {
    const highlightStyle = binding.value.highlightStyle || { backgroundColor: "#f0f0f0" };

    el.addEventListener("dragover", (event) => event.preventDefault());
    el.addEventListener("dragenter", () => applyStyle(el, highlightStyle));
    el.addEventListener("dragleave", () => removeStyle(el, highlightStyle));
    el.addEventListener("drop", (event) => {
      event.preventDefault();
      removeStyle(el, highlightStyle);
      const files = event.dataTransfer.files;
      if (binding.value.uploadFunction && typeof binding.value.uploadFunction === "function") {
        binding.value.uploadFunction(files);
      } else if (binding.value.url) {
        defaultUpload(files, binding.value.url);
      }
    });
  },
};

export default dropImageDirective;
